<template>
  <a-drawer
    :title="title"
    :maskClosable="true"
    :width="drawerWidth"
    placement="right"
    :closable="true"
    @close="handleCancel"
    :visible="visible"
    style="height: 100%;overflow: auto;padding-bottom: 53px;">
    <template slot="title">
      <div style="width: 100%;">
        <span>{{ title }}</span>
        <span style="display:inline-block;width:calc(100% - 51px);padding-right:10px;text-align: right">
          <a-button @click="toggleScreen" icon="appstore" style="height:20px;width:20px;border:0px"></a-button>
        </span>
      </div>

    </template>

    <a-spin :spinning="confirmLoading">
      <a-form-model ref="form" :model="model" :rules="validatorRules">
        <a-form-model-item v-if="item.isInsert" v-for="item in columns" :label="item.columnComment"
                           :prop="item.javaField" :labelCol="labelCol" :wrapperCol="wrapperCol" :key="item.id">
          <a-input v-if="item.htmlType==='input'" :placeholder="'请输入'+item.columnComment"
                   v-model="model[item.javaField]"/>
          <a-textarea v-if="item.htmlType==='textarea'" :placeholder="'请输入'+item.columnComment"
                      v-model="model[item.javaField]"/>
          <j-editor v-if="item.htmlType==='editor'" v-model="model[item.javaField]"/>
          <j-upload v-if="item.htmlType==='file'" v-model="model[item.javaField]"></j-upload>
          <j-image-upload class="avatar-uploader" v-if="item.htmlType==='image'"
                          v-model="model[item.javaField]"></j-image-upload>
          <j-category-select v-if="item.htmlType==='cat_tree'" v-model="model[item.javaField]"
                             :pcode="item.columnExample" :value="model[item.javaField]" :multiple="true"/>
          <j-area-linkage v-if="item.htmlType==='pca'" v-model="model[item.javaField]" type="cascader"/>
          <j-date v-if="item.htmlType=='date'" v-model="model[item.javaField]"
                  :placeholder="'请选择'+item.columnComment"></j-date>
          <j-date v-if="item.htmlType=='datetime'" v-model="model[item.javaField]"
                  :placeholder="'请选择'+item.columnComment" showTime dateFormat="YYYY-MM-DD HH:mm:ss"></j-date>
          <j-dict-select-tag v-if="item.htmlType==='select'" v-model="model[item.javaField]" :dictCode="item.dictCode"
                             :placeholder="'请选择'+item.columnComment"/>
          <j-select-video v-if="item.htmlType==='sel_video'" v-model="model[item.javaField]"
                          :placeholder="'请选择'+item.columnComment"></j-select-video>
          <j-select-member v-if="item.htmlType==='sel_member'" v-model="model[item.javaField]"
                           :placeholder="'请选择'+item.columnComment"></j-select-member>

        </a-form-model-item>
        <a-form-model-item label="用户评论"
                           :labelCol="labelCol" :wrapperCol="wrapperCol" >
          <a-list size="large" style="height: 400px;overflow: auto">
            <div
              v-if="showLoadingMore"
              slot="loadMore"
              :style="{ textAlign: 'center', marginTop: '12px', height: '32px', lineHeight: '32px' }"
            >
              <a-spin v-if="loadingMore" />
              <a-button v-else @click="onLoadMore()">
                更多评论
              </a-button>
            </div>
            <template v-for="(item, index) in commentList">
              <a-list-item :key="index">

                <div class="list-content" style="display: flex">
                  <a-avatar slot="avatar" size="small" :src="item.member.avatarUrl"/>
                  <div class="list-content-item" style="margin-left: 16px">
                    <span>{{item.member.nickName}}</span>
                    <p class="content">{{ item.content }}</p>
                    <p>{{ item.createTime }}</p>
                    <div style="font-weight: bold" v-if="item.commentNum>0" @click="getChildCommentList(item.id,index)">展开{{item.commentNum}}条回复</div>
                  </div>
                </div>
                <div slot="actions">
                  <a @click="showChildComment(item.id)">回复</a>
                </div>
                <div slot="actions">
                  <a v-if="item.status" @click="handleStatus(false,item.id)">屏蔽</a>
                  <a v-else @click="handleStatus(true,item.id)">取消屏蔽</a>
                </div>
              </a-list-item>
              <a-list-item :key="subItem.id" style="margin-left: 20px;" v-for="subItem in item.commentList">
                <div class="list-content" style="display: flex">
                  <a-avatar slot="avatar" size="small" :src="subItem.member.avatarUrl"/>
                  <div class="list-content-item" style="margin-left: 16px">
                    <span>{{subItem.member.nickName}}<span v-if="subItem.parentCommentMemberName"> <a-icon type="caret-right" />{{subItem.parentCommentMemberName}}</span> </span>
                    <p class="content">{{ subItem.content }}</p>
                    <p>{{ subItem.createTime }}</p>
                  </div>
                </div>
                <div slot="actions">
                  <a @click="showChildComment(item.id)">回复</a>
                </div>
                <div slot="actions">
                  <a v-if="item.status" @click="handleStatus(false,item.id)">屏蔽</a>
                  <a v-else @click="handleStatus(true,item.id)">取消屏蔽</a>
                </div>
              </a-list-item>
            </template>


          </a-list>
        </a-form-model-item>
        <a-form-model-item label="发起评论"
                           :labelCol="labelCol" :wrapperCol="wrapperCol" >
          <a-textarea v-model="model.comment"/>
          <a-button type="primary" @click="handleCommentSubmit">
            提交评论
          </a-button>
        </a-form-model-item>

      </a-form-model>

    </a-spin>
    <div class="drawer-bootom-button" v-show="!disableSubmit">
      <a-popconfirm title="确定放弃编辑？" @confirm="handleCancel" okText="确定" cancelText="取消">
        <a-button style="margin-right: .8rem">取消</a-button>
      </a-popconfirm>
      <a-button @click="handleSubmit" type="primary" :loading="confirmLoading">提交</a-button>
    </div>

    <j-modal
      title="评论"
      :visible="childCommentVisible"
      @close="childCommentClose"
      @cancel="childCommentClose"
      @ok="handleChildSubmit"
    >
      <a-textarea v-model="childComment"></a-textarea>
    </j-modal>

  </a-drawer>
</template>
<script>
  import { getAction, postAction } from '@api/manage'
  import { addDynamic, editDynamic, duplicateCheck, queryColumnList } from '@/api/api'
  import JSelectVideo from '@/components/jeecgbiz/JSelectVideo'
  import JSelectMember from '@/components/jeecgbiz/JSelectMember'
  import Area from '@/components/_util/Area'
  import ATextarea from 'ant-design-vue/es/input/TextArea'

  export default {
    name: 'DynamicModal',
    components: {
      ATextarea,
      JSelectVideo,
      JSelectMember
    },
    data() {
      return {
        footer:false,
        childCommentVisible:false,
        childComment:"",
        pageNo:1,
        pageSize:5,
        loading: true,
        loadingMore: false,
        showLoadingMore: false,
        showSubComment:false,
        modalWidth: 800,
        drawerWidth: 700,
        disableSubmit: false,
        validatorRules: {},
        title: '操作',
        visible: false,
        model: {},
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 }
        },
        confirmLoading: false,
        areaData: '',
        columns: [],
        commentList:[],
        showIndex:0,
        dynamicId:"",
        childCommentId:"",
      }

    },
    created() {
      this.initAreaData()
    },
    methods: {
      showChildComment(id){
        this.childCommentVisible=true
        this.childCommentId=id
      },
      handleChildSubmit(){
        postAction('/api/ums/comment/add', {sourceId:this.childCommentId,content:this.childComment,type:"UmsComment"}).then((res) => {
          if (res.success) {
            this.childCommentVisible=false
            this.commentList=[];
            this.getCommentList();
          } else {
            this.$message.warning(res.message)
          }
        })
      },
      childCommentClose(){
        this.childCommentVisible=false
      },
      handleStatus(checked,id){
        let that=this
        postAction("/ums/comment/field/status", {checked:checked,id: id}).then((res) => {
          if (res.success) {
            that.commentList=[];
            that.getCommentList();
          } else {
            that.$message.warning(res.message);
          }
        });
      },
      handleCommentSubmit(){
        postAction('/api/ums/comment/add', {sourceId:this.dynamicId,content:this.model.comment,type:"UmsDynamic"}).then((res) => {
          if (res.success) {
            this.commentList=[];
            this.model.comment=""
            this.getCommentList();
          } else {
            this.$message.warning(res.message)
          }
        })
      },
      onLoadMore(){
        this.loadingMore = true;
        this.pageNo++;
        this.getCommentList();
      },
      getChildCommentList(id,index){
        postAction('/api/ums/comment/list', { sourceId: id}).then((res) => {
          if (res.success) {
            if (res.result.records && res.result.records.length > 0) {
              this.commentList[index].commentList=res.result.records
              this.$forceUpdate();
            }
          } else {
            this.$message.warning(res.message)
          }
        })
      },
      getCommentList() {
        postAction('/api/ums/comment/list', { sourceId: this.dynamicId,pageNo:this.pageNo,pageSize:this.pageSize }).then((res) => {
          this.loadingMore = false;
          this.showLoadingMore=false
          if (res.success) {
            if (res.result.records && res.result.records.length > 0) {
              this.commentList=this.commentList.concat(res.result.records)
              if(res.result.total/this.pageSize>this.pageNo){
                this.showLoadingMore=true
              }
            }
          } else {
            this.$message.warning(res.message)
          }
        })
      },
      loadColumn(record) {
        let that = this
        queryColumnList({
          tableId: 'ee42b034f1534f73b3d75383f69e1ce1',
          pageNo: 1,
          pageSize: 100,
          order: 'asc',
          column: 'sortNo'
        }).then(res => {
          if (res.success) {
            that.columns = res.result.records
            for (let i = 0; i < that.columns.length; i++) {
              that.validatorRules[that.columns[i].javaField] = []
              if (that.columns[i].isRequired) {
                that.validatorRules[that.columns[i].javaField].push({
                  required: 1,
                  message: '请输入' + that.columns[i].columnComment
                })
              }
              if (that.columns[i].fieldValid === 'z') {
                that.validatorRules[that.columns[i].javaField].push({ pattern: /^[0-9]+$/, message: '请输入整数' })
              }
            }
            that.visible = true
            //根据屏幕宽度自适应抽屉宽度
            this.resetScreenSize()
            that.model = Object.assign({}, record)
            that.dynamicId=record.id
            that.commentList=[];
            that.getCommentList();
          }
        }).finally(() => {
          // 这里是无论成功或失败都会执行的方法，在这里关闭loading
          this.loading = false
        })
      },
      initAreaData() {
        if (!this.areaData) {
          this.areaData = new Area(this.$Jpcaa)
        }
      },
      add(mainId) {
        this.refresh()
        this.edit()
      },
      edit(record) {
        this.loadColumn(record)
      },
      refresh() {
        this.type = ''
        this.filePath = ''
        this.messageText = ''
        this.topic = ''
      },
      close() {
        this.$emit('close')
        this.visible = false
        this.disableSubmit = false
        this.$refs.form.resetFields()
      },
      handleCancel() {
        this.close()
      },
      handleSubmit() {
        const that = this
        // 触发表单验证
        this.$refs.form.validate(valid => {
          if (valid) {
            that.confirmLoading = true
            let obj
            if (!this.model.id) {
              obj = addDynamic(this.model)
            } else {
              obj = editDynamic(this.model)
            }
            obj.then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.$emit('ok')
              } else {
                that.$message.warning(res.message)
              }
            }).finally(() => {
              that.confirmLoading = false
              that.close()
            })
          } else {
            return false
          }
        })
      },
      //窗口最大化切换
      toggleScreen() {
        if (this.modaltoggleFlag) {
          this.modalWidth = window.innerWidth
        } else {
          this.modalWidth = 800
        }
        this.modaltoggleFlag = !this.modaltoggleFlag
      },
      // 根据屏幕变化,设置抽屉尺寸
      resetScreenSize() {
        let screenWidth = document.body.clientWidth
        if (screenWidth < 500) {
          this.drawerWidth = screenWidth
        } else {
          this.drawerWidth = 700
        }
      }

    }

  }

</script>

<style lang="less" scoped>

  .drawer-bootom-button {
    position: absolute;
    bottom: -8px;
    width: 100%;
    border-top: 1px solid #e8e8e8;
    padding: 10px 16px;
    text-align: right;
    left: 0;
    background: #fff;
    border-radius: 0 0 2px 2px;
  }

  .ant-avatar-lg {
    width: 48px;
    height: 48px;
    line-height: 48px;
  }

  .list-content-item {
    color: rgba(0, 0, 0, .45);
    display: inline-block;
    vertical-align: middle;
    font-size: 14px;
    margin-left: 40px;
    span {
      line-height: 20px;
      font-weight: 600;
    }
    .content{
      color: black;
    }
    p {
      margin-top: 4px;
      margin-bottom: 0;
      line-height: 22px;
    }
  }
</style>